package za.ac.wits.was.courses;

import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import za.ac.wits.was.courses.allocations.CourseAllocations;
import za.ac.wits.was.disciplines.Discipline;

/**
 *
 * @author Salman Noor : School of Electrical and Information Engineering
 * @Copyright: Wits University 2013 - All Rights Reserved
 * @email: salmannoor74415@gmail.com
 * @License: BSD License (http://www.linfo.org/bsdlicense.html)
 */
@Service
@Transactional
public class CourseService {

    private SessionFactory sessionFactory;

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    
    public List<Course> getAllCourses() {
        Session sess = this.sessionFactory.openSession();
        List<Course> theList = sess.createQuery("from Course").list();
        sess.flush();
        sess.close();
        return theList;
    }
    
    
        public Course createNewCourse(Course newCourse) {
        Session sess = this.sessionFactory.openSession();
       Discipline dc = (Discipline) sess.get(Discipline.class, newCourse.getDiscipline_id());
       newCourse.setDiscipline(dc);
        sess.save(newCourse);
        sess.flush();
        sess.close();
        return newCourse;
    }
    
    
        public Course updateCourse(Course updatedCourse) {
        Session sess = this.sessionFactory.openSession();
        Course tc = (Course) sess.get(Course.class, updatedCourse.getCourse_id());
        Discipline dc = (Discipline) sess.get(Discipline.class, updatedCourse.getDiscipline_id());
        tc.setDiscipline(dc);
        tc.setCourse_name(updatedCourse.getCourse_name());
        tc.setCourse_code(updatedCourse.getCourse_code());
        tc.setCourse_slot(updatedCourse.getCourse_slot());
        tc.setCourse_hours(updatedCourse.getCourse_hours());
        tc.setStart_time(updatedCourse.getStart_time());
        tc.setEnd_time(updatedCourse.getEnd_time());
        tc.setSemester(updatedCourse.getSemester());
        tc.setWeekday(updatedCourse.getWeekday());
        sess.saveOrUpdate(tc);
        sess.flush();
        sess.close();
        return tc;
    }
        
        
    public Course deleteCourse(Course existingCourse) {
        Session sess = this.sessionFactory.openSession();
        Course couseToBeDeleted = (Course) sess.get(Course.class, existingCourse.getCourse_id());
        
        for(CourseAllocations ax :couseToBeDeleted.getCourse_allocations()){
        sess.delete(ax);
        }
        
        sess.delete(couseToBeDeleted);
        sess.flush();
        sess.close();
        return existingCourse;
    }
}
